<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-04-27
 * Time: 16:44
 */


/*
    * 增加积分  //0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮  7签到 8连续签到积分 9积分商品
    * @param array $arr
    * @param string $key
    * @param strgin $val
    * @return int 0/1
    *
    */
function addCredit($openid,$credit,$orderid,$wid,$type)
{
    $data['openid'] = $openid;
    $data['credit'] = $credit;
    $data['orderid'] = $orderid;//通过day查对应的积分
    $data['type'] = $type;  //0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮  7签到 8连续签到积分
    $data['wid'] = $wid;
    $data['time'] = date("Y-m-d H:i:s");
    M('credit_log')->add($data);


    //member表加积分
    $member = getMember($wid,$openid);
    $data['credit'] = $member['credit'] +$credit;
    M('member')->where(['openid'=>$openid])->save($data);
}

   /*
    * 判断某个二维数组k对应的v是否为传入的值
    * @param array $arr
    * @param string $key
    * @param strgin $val
    * @return int 0/1
    *
    */
function getVal($arr,$key,$val){
    $bool = false;
    if(is_array($arr)){
        foreach($arr as $k=>$v){
            if($v[$key] == $val){
                $bool = true;
                break;
            }
        }
        return $bool;
    }else{
        return false;
    }
}


/*
    * 易联云测试添加授权打印机
    * @param $machineCode
    * @param $msign or $qrKey
    * @param $accessToken
    * */
function addprinter($machineCode,$msign,$accessToken)
{
    vendor('openapi-sdk.lib.YLYOpenApiClient');
    $api = new \YLYOpenApiClient();
    $timesTamp = time();
    echo $api->addPrint($machineCode,$msign,$accessToken,$timesTamp);

}
/*
    * 易联云测试删除授权打印机
    * @param $machineCode
    * @param $accessToken
    * */
function deleteprinter($machineCode,$accessToken)
{
    vendor('openapi-sdk.lib.YLYOpenApiClient');
    $api = new \YLYOpenApiClient();

    $timesTamp = time();
    echo $api->deletePrint($machineCode,$accessToken,$timesTamp);

}
/*
 * 给上级添加佣金
 * @param $wid
 * @param $type 佣金来源：0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮
 * @param $orderid 订单id
 * @param $openid
 * @param $field1 一级分销字段名称
 * @param $field2 二级分销字段名称
 * @param $price 订单金额
 */
function addCommission($wid,$type,$orderid,$openid,$field1,$field2,$price){
    //开启事务
    M()->startTrans();
    $level1 =[];
    $r = [];
    //获取上级信息 两级
    $member = M('member')->where(['openid'=>$openid])->find();
    if(!$member){
        return false;
    }
    //团队分红
    $r[] = addTeamBonus($wid,$type,$orderid,$openid,$price);
    //获取后台设置信息。一级分销，还是二级分销
    $wechat = M('wechat')->where(['wid'=>$wid])->find();
    $commission_level = $wechat['commission_level'];

    //查佣金表，获取佣金设置
    $commission = M('commission_proportion')->where(['wid'=>$wid])->find();
    $commission1 = $commission[$field1];
    $commission2 =  $commission[$field2];
    if(!$commission){
        return false;
    }
    //一级
    if($member['agent']>0 && $commission1>0){
        $level1 = M('member')->where(['mid'=>$member['agent']])->find();
        $level1_info = getMember($wid,$level1['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level1 && $level1_info['has_card']){
            $data['wid'] = $wid;
            $data['money'] = $price*$commission1/100;
            $data['mid'] = $level1['mid'];
            $data['type'] = $type;
            $data['fmid'] = $member['mid'];//佣金来源mid
            $data['orderid'] = $orderid;
            $data['is_withdraw'] = 0;
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['level'] =1;//几级
            $data['commission_proportion'] =$commission1; //佣金比例
            $r[] = M('commission')->add($data);
        }else{
            $r[] = true;
        }
    }
    //二级
    if(($level1['agent']>0) && ($commission2>0) && ($commission_level>1)){
        $level2 = M('member')->where(['mid'=>$level1['agent']])->find();
        $level2_info = getMember($wid,$level2['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level2 && $level2_info['has_card']){
            $data2['wid'] = $wid;
            $data2['money'] = $price*$commission2/100;
            $data2['mid'] = $level2['mid'];
            $data2['fmid'] = $member['mid'];//佣金来源mid
            $data2['type'] = $type;
            $data2['orderid'] = $orderid;
            $data2['is_withdraw'] = 0;
            $data2['time'] = date('Y-m-d H:i:s',time());
            $data2['level'] =2;//几级
            $data2['commission_proportion'] =$commission2;//佣金比例
            $r[] = M('commission')->add($data2);
        }else{
            $r[] = true;
        }
    }
    if(in_array(false,$r,true)){
        M()->rollback();
        return false;
    }else{
        M()->commit();
        return true;
    }
}

/*
 * 餐饮  给上级添加佣金
 * @param $wid
 * @param $type 佣金来源：0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮
 * @param $orderid 订单id
 * @param $openid
 */
function addDishesCommission($wid,$type,$orderid){
    //开启事务
    M()->startTrans();
    $level1 = [];
    $r = [];
    $price = 0;//分销商品总钱
    $price_one = 0;//一级佣金
    $price_two = 0;//二级佣金

    //订单详情
    $order = M('takeout_order')->where(['id'=>$orderid])->find();
    //查询订单及商品信息判断是否参与分销
    $list = M('takeout_order')->alias('o')
        ->field('o.*,g.money as gmoney,g.number as gnum,d.is_commission,d.commission_one_in,d.commission_two_in,d.commission_one_out,d.commission_two_out,d.commission_type as ctype')
        ->join('tp_takeout_goods g on g.order_id = o.id')
        ->join('tp_takeout_dishes d on d.id = g.dishes_id')
        ->where(['o.id'=>$orderid])
        ->select();
    //计算应该发送的佣金额度
    foreach($list as $k=>$v){
        //是否参与分销
        if($v['is_commission'] == 1){
            //判断订单未店内还是店外订单，以及商品佣金发放的为店内还是店外订单
            if(($v['type'] == $v['ctype']) || $v['ctype'] == 3){
                $price = $price + $v['gmoney'];
                switch($v['type']) {
                    //外卖
                    case 1:
                        $price_one = $price_one + ($v['gmoney'] * $v['commission_one_out'] *$v['gnum'] /100);
                        $price_two = $price_two + ($v['gmoney'] * $v['commission_two_out'] *$v['gnum'] /100);
                        break;
                    //店内
                    case 2:
                        $price_one = $price_one + ($v['gmoney'] * $v['commission_one_out'] *$v['gnum'] /100);
                        $price_two = $price_two + ($v['gmoney'] * $v['commission_two_out'] *$v['gnum'] /100);
                        break;
                }

            }
        }
    }
    //获取上级信息 两级
    $member = M('member')->where(['mid'=>$order['user_id']])->find();
    if(!$member){
        return false;
    }
    //团队分红
    $r[] = addTeamBonus($wid,$type,$orderid,$member['openid'],$price);
    //获取后台设置信息。一级分销，还是二级分销
    $wechat = M('wechat')->where(['wid'=>$wid])->find();
    $commission_level = $wechat['commission_level'];
    //一级
    if($member['agent']>0 && $price_one>0){
        $level1 = M('member')->where(['mid'=>$member['agent']])->find();
        $level1_info = getMember($wid,$level1['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level1 && $level1_info['has_card']){
            $data['wid'] = $wid;
            $data['money'] = $price_one;
            $data['mid'] = $level1['mid'];
            $data['fmid'] = $member['mid'];//佣金来源mid
            $data['type'] = $type;
            $data['orderid'] = $orderid;
            $data['is_withdraw'] = 0;
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['level'] =1;//几级
            $data['commission_proportion'] =0; //佣金比例
            $r[] = M('commission')->add($data);
        }else{
            $r[] = true;
        }
    }
    //二级
    if(($level1['agent']>0) && ($price_two>0) && ($commission_level>1)){
        $level2 = M('member')->where(['mid'=>$level1['agent']])->find();
        $level2_info = getMember($wid,$level2['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level2 && $level2_info['has_card']){
            $data2['wid'] = $wid;
            $data2['money'] = $price_two;
            $data2['mid'] = $level2['mid'];
            $data2['fmid'] = $member['mid'];//佣金来源mid
            $data2['type'] = $type;
            $data2['orderid'] = $orderid;
            $data2['is_withdraw'] = 0;
            $data2['time'] = date('Y-m-d H:i:s',time());
            $data2['level'] =2;//几级
            $data2['commission_proportion'] =0;//佣金比例
            $r[] = M('commission')->add($data2);
        }else{
            $r[] = true;
        }
    }
    if(in_array(false,$r,true)){
        M()->rollback();
        return false;
    }else{
        M()->commit();
        return true;
    }
}
/*
 * 商品核销 给上级添加佣金
 * @param $wid
 * @param $type 佣金来源：0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮
 * @param $orderid 订单id
 * @param $openid
 * @param $commission1 一级分销比例
 * @param $commission2 二级分销比例
 * @param $price 订单金额
 */
function addGoodCommission($wid,$type,$orderid,$openid,$commission1,$commission2,$price){
    //开启事务
    M()->startTrans();
    $level1 = [];
    $r = [];
    //获取上级信息 两级
    $member = M('member')->where(['openid'=>$openid])->find();
    if(!$member){
        return false;
    }
    //团队分红
    $r[] = addTeamBonus($wid,$type,$orderid,$openid,$price);
    //获取后台设置信息。一级分销，还是二级分销
    $wechat = M('wechat')->where(['wid'=>$wid])->find();
    $commission_level = $wechat['commission_level'];
    //一级
    if($member['agent']>0 && $commission1>0){
        $level1 = M('member')->where(['mid'=>$member['agent']])->find();
        $level1_info = getMember($wid,$level1['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level1 && $level1_info['has_card']){
            $data['wid'] = $wid;
            $data['money'] = $price*$commission1/100;
            $data['mid'] = $level1['mid'];
            $data['fmid'] = $member['mid'];//佣金来源mid
            $data['type'] = $type;
            $data['orderid'] = $orderid;
            $data['is_withdraw'] = 0;
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['level'] =1;//几级
            $data['commission_proportion'] =$commission1; //佣金比例
            $r[] = M('commission')->add($data);
        }else{
            $r[] = true;
        }
    }
    //二级
    if(($level1['agent']>0) && ($commission2>0) && ($commission_level>1)){
        $level2 = M('member')->where(['mid'=>$level1['agent']])->find();
        $level2_info = getMember($wid,$level2['openid']);
        //判断是否同城卡是否可以使用，并且有上级
        if($level2 && $level2_info['has_card']){
            $data2['wid'] = $wid;
            $data2['money'] = $price*$commission2/100;
            $data2['mid'] = $level2['mid'];
            $data2['fmid'] = $member['mid'];//佣金来源mid
            $data2['type'] = $type;
            $data2['orderid'] = $orderid;
            $data2['is_withdraw'] = 0;
            $data2['time'] = date('Y-m-d H:i:s',time());
            $data2['level'] =2;//几级
            $data2['commission_proportion'] =$commission2;//佣金比例
            $r[] = M('commission')->add($data2);
        }else{
            $r[] = true;
        }
    }
    if(in_array(false,$r,true)){
        M()->rollback();
        return false;
    }else{
        M()->commit();
        return true;
    }
}
/*
 * 添加团队分红
 * @param $wid
 * @param $type 佣金来源：0店铺入驻 1同城卡 2信息发布 3店铺升级 4商品核销 5送礼物 6餐饮
 * @param $orderid 订单id
 * @param $openid
 * @param $price 订单金额
 */
function addTeamBonus($wid,$type,$orderid,$openid,$price){

    $r = true;
    $price_leader2 = 0;
    $data =[];
    $leader2s = [];
    //获取信息
    $member = M('member')->where(['openid'=>$openid])->find();

    if(!$member || ($member['team_leader'] == 0 && $member['is_team_leader'] != 1)){
        return true;
    }
    //获取后台设置信息。
    $wechat = M('wechat')->where(['wid'=>$wid])->find();
    //队长分红比例
    $leader_bonus = $wechat['leader_bonus'];
    //队长应得的钱(未扣除副队长的钱)
    $price_leader = $leader_bonus * $price/100;

    //获取团队设置
    $commission_set = M('commission_team')->where(['status'=>1,'leaderid'=>$member['team_leader']])->find();
    //副队长比例大于0
    if($commission_set['leader2_commission']>0 && $price_leader>0){
        //查团队内是否有副队长
        $leader2s = M('member')->where(['team_leader'=>$member['team_leader'],'is_leader2'=>1])->select();
        //副队长应得的钱
        $price_leader2 = $price_leader*$commission_set['leader2_commission']/100;
        //给副队长分钱
        if($leader2s && $price_leader2 >=0.01){
            foreach($leader2s as $k=>$v){
                $info = getMember($wid,$v['openid']);
                //判断是否开通同城卡
                if(!$info['has_card']){
                    continue;
                }
                $data[$k]['wid'] = $wid;
                $data[$k]['money'] = $price_leader2;
                $data[$k]['mid'] = $v['mid'];
                $data[$k]['type'] = $type;
                $data[$k]['fmid'] = $member['mid'];//分红来源mid
                $data[$k]['orderid'] = $orderid;
                $data[$k]['is_withdraw'] = 0;
                $data[$k]['time'] = date('Y-m-d H:i:s',time());
                $data[$k]['level'] =0;//几级
                $data[$k]['mold'] = 1;
                $data[$k]['commission_proportion'] =$commission_set['leader2_commission']; //分红比例
                unset($info);
            }
        }
    }
    //队长实际应得到的钱
    $price_leader_final = $price_leader - ($price_leader2*count($leader2s));
    $kk = count($data)==0?0:count($data)+1;
    if($price_leader_final>=0.01){
        $data[$kk]['wid'] = $wid;
        $data[$kk]['money'] = $price_leader_final;
        //队长自己消费时候
        if($member['is_team_leader'] == 1){
            //给队长分钱
            $data[$kk]['mid'] = $member['mid'];
        }else{
            //给副队长分钱
            $data[$kk]['mid'] = $member['team_leader'];
        }

        $data[$kk]['type'] = $type;
        $data[$kk]['fmid'] = $member['mid'];//分红来源mid
        $data[$kk]['orderid'] = $orderid;
        $data[$kk]['is_withdraw'] = 0;
        $data[$kk]['time'] = date('Y-m-d H:i:s',time());
        $data[$kk]['level'] =0;//几级
        $data[$kk]['mold'] = 1;//0佣金 1分红
        $data[$kk]['commission_proportion'] =$wechat['leader_bonus']; //分红比例

    }
    //全部合格，一起分红，一起开心
    if($data){
        //存入全部数据
        $r = M('commission')->addAll($data);
        if(!$r){
            return false;
        }else{
            return true;
        }
    }
    return true;
}


/*
 * 获取用户信息
 * @param $wid
 * @param $openid
 * @return $info 会员信息，包括同城卡是否过期或者开通,未提现佣金
 */
function getMember($wid,$openid)
{
    $info= M('member')->where(['openid'=>$openid])->find();
    if(!$info){
        return false;
    }
    //同城卡是否可以使用
    $map['wid']=$wid;
    $map['openid']=$openid;
    $map['is_pay']=1;
    $map['end_time'] = ['GT', date('Y-m-d H:i:s', time())];
    $card = M('card_log')->where($map)->find();
    $info['has_card'] = $card?true:false;

    //计算未提现的佣金
    $commission_wite = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>0,'mold'=>0])->sum('money');
    $info['commission_wite'] = $commission_wite?$commission_wite:0;
    //已入账的
    $commission_finish = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>1,'mold'=>0])->sum('money');
    $info['commission_finish'] = $commission_finish?$commission_finish:0;
    //总佣金
    $commission = M('commission')->where(['mid'=>$info['mid'],'mold'=>0])->sum('money');
    $info['commission'] = $commission?$commission:0;
    //分享金收入列表
    $commission_in_list = M('commission')->alias('a')->field('a.*, b.nickname')->join('tp_member b on a.fmid = b.mid')->where(['a.mid'=>$info['mid'],'mold'=>0])->select();
    $info['commission_in_list'] = $commission_in_list;
    //分享金支出列表(提现)
    $map2['wid'] = session('wid');
    $map2['openid'] = I('openid');
    $map2['type'] = 0;
    $map2['status'] = ['gt','0'];
    $list = M('commission_putmoney')->where($map2)->order('createtime desc')->select();
    $info['commission_out_list'] = $list;

    return $info;
}


/*
 * 获取用户信息
 * @param $wid
 * @param $mid
 * @return $info 会员信息，包括同城卡是否过期或者开通,未提现佣金
 */
function getMemberByMid($wid,$mid)
{
    $info= M('member')->where(['mid'=>$mid])->find();
    if(!$info){
        return false;
    }
    //同城卡是否可以使用
    $map['wid']=$wid;
    $map['openid']=$info['openid'];
    $map['is_pay']=1;
    $map['end_time'] = ['GT', date('Y-m-d H:i:s', time())];
    $card = M('card_log')->where($map)->find();
    $info['has_card'] = $card?true:false;

    //计算未提现的佣金
    $commission_wite = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>0])->sum('money');
    $info['commission_wite'] = $commission_wite?$commission_wite:0;
    //已入账的
    $commission_finish = M('commission')->where(['mid'=>$info['mid'],'is_withdraw'=>1])->sum('money');
    $info['commission_finish'] = $commission_finish?$commission_finish:0;
    //总佣金
    $commission = M('commission')->where(['mid'=>$info['mid']])->sum('money');
    $info['commission'] = $commission?$commission:0;
    //分享金收入列表
    $commission_in_list = M('commission')->alias('a')->field('a.*, b.nickname')->join('tp_member b on a.mid = b.mid')->where(['a.mid'=>$info['mid']])->select();
    $info['commission_in_list'] = $commission_in_list;
    //分享金支出列表?
    $info['commission_out_list'] = [];

    return $info;
}


/*
 *将推荐信息存入表中
 * @param $type 推荐类型：文章（咨询）news、圈子quan、话题topic、用户member、商家shop、商品goods、活动huodong、优惠券coupon、广告ad
 * @param $id 被推荐类型id
 * @param $wid
 * @param $status  0未推荐，1已推荐
 */
function tui($type,$id,$wid,$status,$content ='')
{
    $eq['type'] = $type;
    $eq['aid'] = $id;
    $eq['wid'] = $wid;
    if($content){
        $eq['content'] = $content;
    }
    $list = M('tui')->where($eq)->find();
    $tui = M('tui_cate')->where(['type'=>$type,'wid'=>$wid])->find();
    $data['tid'] = $tui['id'];
    $data['type'] = $type;
    $data['aid'] = $id;
    $data['wid'] = $wid;
    $data['status'] = $status;
    if($content){
        $data['content'] = $content;
    }
    $data['createtime'] = date("Y-m-d H:i:s",time());
    if($list){
        $r = M('tui')->where($eq)->save($data);
    }else{
        $r = M('tui')->add($data);
    }
    if($r){
        return true;
    }else{
        return false;
    }
}

//请求接口获得模板消息
function getTemplate($offset=0,$count=20)
{
    $wid = session('wid');
    //获取微信的access_token
    $fcount = M("form")->where(['wid'=>$wid])->count();
    if($fcount <25){
        $access_token = get_access_token_mp();
        $url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=".$access_token;
        //请求参数
        $dd = array();
        $dd['offset']=$offset;
        $dd['count']=$count;
        $result = ihttp_post($url,json_encode($dd));
        $result = json_decode($result,true);
        if($result['errmsg'] == "ok"){//请求成功存入数据库
            if($offset <20){
                M('form')->where(['wid'=>$wid])->delete();
            }
            foreach($result['list'] as $v){
                $data['wid']= $wid;
                $data['template_id']=$v['template_id'];
                $data['title'] = $v['title'];
                $data['content']= $v['content'];
                $data['example']=$v['example'];
                $data['createtime'] = date("Y-m-d H:i:s",time());
                $have = M('form')->where(['wid'=>$wid,'template_id'=>$v['template_id']])->find();
                if(!$have){
                    M('form')->add($data);
                }
                unset($have);
                unset($data);
            }
        }
        if($offset <20 && $fcount <20){
            getTemplate(20,20);
        }
    }

}

/*
 * 发送直播开播通知
 * @param $id       直播表id
 * @return bool
 */
function sendShenpiMessage($id,$type)
{
    if($type=='withdraw'){//提现
        $list = M('withdraw')->where(['id'=>$id])->find();
        $types = '商家申请提现';
        $star = $list['createtime'];
        $end = $star;
        //会员昵称
        $member = M('member')->alias('m')->field('m.*')->join('tp_shop s on s.openid = m.openid')->where(['shop_id'=>$list['shop_id']])->find();
    }
    if($type == 'renling'){
        $list = M('renling')->where(['id'=>$id])->find();
        $star = $list['last_time'];
        $end = $star;
        $types = '认领申请审核';
        //会员昵称
        $member = M('member')->alias('m')->field('m.*')->join('tp_shop s on s.openid = m.openid')->where(['shop_id'=>$list['shop_id']])->find();
    }
    if($type == 'zhibo'){
        $list = M('zhibo')->where(['id'=>$id])->find();
        $star = $list['create_time'];
        $end = $list['last_time'];
        $types = '直播申请审核';
        //会员昵称
        $member = M('member')->alias('m')->field('m.*')->join('tp_shop s on s.openid = m.openid')->where(['shop_id'=>$list['shop_id']])->find();
    }
    if($type == 'ruzhu'){
        $list = M('shop')->where(['shop_id'=>$id])->find();
        $star = $list['create_time'];
        $end = $star;
        $types = '入驻申请审核';
        //会员昵称
        $member = M('member')->alias('m')->field('m.*')->join('tp_shop s on s.openid = m.openid')->where(['shop_id'=>$list['shop_id']])->find();
    }
    if($type == 'dianpu'){
        $list = M('level_order')->where(['id'=>$id])->find();
        $star = $list['create_time'];
        $end = $star;
        $types = '店铺升级申请审核';
        //会员昵称
        $member = M('member')->alias('m')->field('m.*')->join('tp_shop s on s.openid = m.openid')->where(['shop_id'=>$list['shop_id']])->find();
    }
    if($type == 'leader'){
        $list = M('commission_team')->where(['id'=>$id])->find();
        $star = $list['create_time'];
        $end = $star;
        $types = '团队分销申请队长';
        $member = M('member')->where(['mid'=>$list['mid']])->find();;
    }

    $wid = $list['wid'];
    $wechat = M('wechat')->alias('w')->field('u.*')->join('tp_user u on u.uid=w.uid')->where(['wid'=>$wid])->find();

    $openid =$wechat['openid'];
    if(!$openid){
        return false;
    }

    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%申请审批%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$types, //申请类型
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$star, //开始时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$end,//结束时间
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$member['nickname'],//会员昵称
            "color"=>"#9b9b9b"
        ),
    );

    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    //$str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
    //file_put_contents('oshen.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendZhiboMessage($id);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送直播开播通知
 * @param $id       直播表id
 * @return bool
 */
function sendZhiboMessage($openid,$id)
{
    $shop = M("Zhibo")->alias('z')->field('z.*,m.nickname,m.openid')->join('tp_member m on m.mid = z.member_id')->where(['id'=>$id])->find();
    if(!$shop){
        return false;
    }
    if(!$openid){
        return false;
    }
    $wid = $shop['wid'];
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%预约直播%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$shop['title'], //直播标题
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$shop['start_date']." ".$shop['start_time']."-".$shop['end_time'], //直播时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>"您关注的主播开始直播了，快来观看吧",//直播提示
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>"暂无",//直播嘉宾
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$shop['start_date']." ".$shop['start_time'],//开播时间
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>"暂无",//奖金
            "color"=>"#9b9b9b"
        ),
        "keyword7"=>array(
            "value"=>$shop['nickname'],//主播
            "color"=>"#9b9b9b"
        ),
    );

    $page = "pages/quan/video/list?idx=1";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
//    $str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
//    file_put_contents('o.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendZhiboMessage($id);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
/*
 * 发送入驻成功通知
 * @param $shop_id       shop_id
 * @return bool
 */
function sendRuzhuMessage($shop_id)
{
    $shop = M("shop")->where(['shop_id'=>$shop_id])->find();
    if(!$shop){
        return false;
    }
    if(!$shop['openid']){
        return false;
    }
    $openid = $shop['openid'];
    $wid = $shop['wid'];
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%入驻成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$shop['name'], //店铺名称
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$shop['last_time'], //入驻时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>"恭喜您入住成功，马上进入小程序完善店铺信息吧！",//温馨提示
            "color"=>"#9b9b9b"
        ),
        /*"keyword4"=>array(
            "value"=>"五星级",//星级
            "color"=>"#9b9b9b"
        ),*/
    );

    $page = "pages/mine/shop/edit?shop_id={$shop['shop_id']}&wid={$shop['wid']}";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    //$str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
    //file_put_contents('o.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendRuzhuMessage($shop_id);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送预约成功通知
 * @param $id       yuyue表id
 * @return bool
 */
function sendYuyueMessage($id)
{
    $yuyue = M("shop_yuyue")->alias('y')->field('y.remark as r,s.*')->join('tp_shop s on s.shop_id = y.shop_id')->where(['id'=>$id])->find();
    if(!$yuyue){
        return false;
    }
    if(!$yuyue['openid']){
        return false;
    }
    $openid = $yuyue['openid'];
    $wid = $yuyue['wid'];
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%预约成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$yuyue['name'], //店铺名称
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$yuyue['tel'], //联系方式
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$yuyue['r'],//备注
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>"取消预约请提前联系商家",//温馨提示
            "color"=>"#9b9b9b"
        ),
    );

    $page = "pages/mine/yuyue/list";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
//    $str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
//    file_put_contents('o.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendYuyueMessage($id);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}



/*
 * 发送审核通过通知
 * @param $id       zhibo表id
 * @param $type     类型：直播；zhibo，生成小程序：mini
 * @return bool
 */
function sendAuditMessage($id,$type)
{
    $dd = array();
    //查询直播表内容信息
    if($type =='zhibo'){
        $zhibo = M('zhibo')->alias('z')->field('z.*,m.openid,s.name')
            ->join("tp_member m on m.mid = z.member_id")
            ->join("tp_shop s on s.shop_id = z.shop_id")
            ->where(['z.id'=>$id])
            ->find();
        $content = $zhibo['title'];//申请内容
        $msg = "点击打开小程序，开始你的直播吧！";//温馨提示
        $page = "pages/index/index";//打开页面
        $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    }
    if($type =='mini'){
        $zhibo = M('shop')->where(['shop_id'=>$id])->find();
        $content = "生成小程序";//申请内容
        $msg = "生成独立小程序审核通过！";//温馨提示
    }
    if($type == 'withdraw'){
        $zhibo = M('withdraw')->alias('w')->field('w.createtime as last_time,w.shop_id,s.name,s.openid,s.wid')
            ->join("tp_shop s on s.shop_id = w.shop_id")
            ->where(['id'=>$id])->find();
        $content = '提现';
        $msg = "申请提现审核通过！";//温馨提示
        $page = "pages/index/index";//打开页面
        $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    }
    if($type == 'level'){
        $zhibo = M('level_order')->alias('w')->field('w.create_time as last_time,w.shop_id,s.name,s.openid,s.wid')
            ->join("tp_shop s on s.shop_id = w.shop_id")
            ->where(['id'=>$id])->find();
        $content = '店铺升级';
        $msg = "店铺升级审核通过！";//温馨提示
        $page = "pages/mine/shop/shop";//打开页面
        $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    }
    if($type == 'team'){
        $zhibo = M('commission_team')->alias('t')->field('t.create_time as last_time,t.team_name as name,m.openid,t.wid')
            ->join("tp_member m on m.mid = t.leaderid")
            ->where(['id'=>$id])->find();
        $content = '申请成为队长';
        $msg = "申请成为队长审核通过！";//温馨提示
        $page = "pages/index/index";//打开页面
        $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    }
    if(!$zhibo['openid']){
        return false;
    }
    $wid = $zhibo['wid'];
    $openid = $zhibo['openid'];
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%审核通过%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }

    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$zhibo['name'], //店铺名称
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$content, //申请内容
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>"通过",//审核结果
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$zhibo['last_time'],//通过时间
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$msg,//温馨提示
            "color"=>"#9b9b9b"
        ),
    );

    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;

    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    /*$str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
    $a = file_put_contents('osss.txt',$str,FILE_APPEND);*/
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendAuditMessage($id,$type);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}


/*
 * 发送帖子回复通知
 * 普通订单支付成功后用户收到模板消息，同时商家也要收到消息
 * @param $openid       接收者opneid
 * @param $pages    打开后跳转到小程序路径
 * @param $part    帖子场合
 * @param $id    帖子id
 * @return bool
 */
function sendReplyMessage($openid,$part,$wid,$id)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%帖子回复%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
   //查出回复详情
    switch($part){
        case 'news':
            $part_name = '资讯';
            //帖子信息及被评论人信息
            $news = M('news_reply')->alias('np')
                ->field('n.title,np.openid,np.reply_openid,np.content,np.last_time,np.nid')
                ->join('tp_news n on n.id = np.nid','LEFT')
                ->join('tp_member m on m.openid = np.reply_openid',"LEFT")
                ->where(['np.wid'=>$wid,'np.id'=>$id])
                ->find();
            $pages = "pages/quan/news/detail?id=".$news['nid'];
            if(mb_strlen($news['title'],'utf8')>10){
                $title = mb_substr($news['title'],0,10,'utf-8')."...";
            }else{
                $title = $news['title'];
            }
            if(mb_strlen($news['content'],'utf8')>20){
                $content = mb_substr($news['content'],0,20,'utf-8')."...";
            }else{
                $content = $news['content'];
            }
            break;
        case 'video':
            $part_name = '视频';
            //帖子信息及被评论人信息
            $news = M('quan_reply')->alias('np')
                ->field('n.title,np.openid,np.reply_openid,n.content,np.content as rcontent,np.last_time,np.qid')
                ->join('tp_quan n on n.id = np.qid','LEFT')
                ->join('tp_member m on m.openid = np.reply_openid',"LEFT")
                ->where(['np.wid'=>$wid,'np.id'=>$id])
                ->find();
            $pages = "pages/quan/video/video?id=".$news['qid'];
            if($news['content']){
                $title = mb_substr($news['content'],0,10,'utf-8')."...";
            }else{
                $title = "发布的视频";
            }
            if(mb_strlen($news['rcontent'],'utf8')>20){
                $content = mb_substr($news['rcontent'],0,20,'utf-8')."...";
            }else{
                $content = $news['rcontent'];
            }
            break;
        case 'question':
            $part_name = '问答';
            //帖子信息及被评论人信息
            $news = M('quan_reply')->alias('np')
                ->field('n.title,np.openid,np.reply_openid,n.content,np.content as rcontent,np.last_time,np.qid,np.pid')
                ->join('tp_quan n on n.id = np.qid','LEFT')
                ->join('tp_member m on m.openid = np.reply_openid',"LEFT")
                ->where(['np.wid'=>$wid,'np.id'=>$id])
                ->find();
            $pages = "pages/quan/question/details?id=".$news['qid'];
            $reply = M('quan_reply')->where(['id'=>$news['pid']])->find();
            if(mb_strlen($reply['content'],'utf-8')>10){
                $title = mb_substr($reply['content'],0,10,'utf-8')."...";
            }else{
                $title = $reply['content'];
            }
            if(mb_strlen($news['rcontent'],'utf8')>20){
                $content = mb_substr($news['rcontent'],0,20,'utf-8')."...";
            }else{
                $content = $news['rcontent'];
            }
            break;
        case 'quan':
            $part_name = '同城圈';
            //帖子信息及被评论人信息
            $news = M('quan_reply')->alias('np')
                ->field('n.title,np.openid,np.reply_openid,n.content,np.content as rcontent,np.last_time,np.qid')
                ->join('tp_quan n on n.id = np.qid','LEFT')
                ->join('tp_member m on m.openid = np.reply_openid',"LEFT")
                ->where(['np.wid'=>$wid,'np.id'=>$id])
                ->find();
            $pages = "pages/quan/detail?id=".$news['qid'];
            if($news['content']){
                $title = mb_substr($news['content'],0,10,'utf-8')."...";
            }else{
                $title = "发布的帖子";
            }
            if(mb_strlen($news['rcontent'],'utf8')>20){
                $content = mb_substr($news['rcontent'],0,20,'utf-8')."...";
            }else{
                $content = $news['rcontent'];
            }
            break;

    }
    //查出评论人信息
    $member = M('member')->where(['wid'=>$wid,'openid'=>$news['openid']])->find();

    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid


    $value = array(
        "keyword1"=>array(
            "value"=>$part_name, //帖子场合
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$title, //您的帖子
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$member['nickname'],//回贴人
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$content,//回帖内容
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>"请打开小程序查看最新回复",//温馨提示
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>$news['last_time'],//回复时间
            "color"=>"#9b9b9b"
        ),
    );
    $page = $pages;//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendReplyMessage($openid,$pages,$part,$wid,$id);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
/*
 * 发送购买成功通知
 * 普通订单支付成功后用户收到模板消息，同时商家也要收到消息
 * @param $openid       opneid
 * @param $out_trade_no  订单号
 * @param $type 类型。商家shop 用户member
 * @return bool
 */
function sendOrderMessage($openid,$out_trade_no,$wid,$type)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%购买成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('order')->alias('o')->field("o.*,s.name")->join('tp_shop s on s.shop_id = o.shop_id')->where(['out_trade_no'=>$out_trade_no])->find();
    //组装data

    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$info['name'], //购买地点
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$info['create_time'], //购买时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$info['title'],//物品名称
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$out_trade_no,//交易单号
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>"￥".$info['pay_money']."元",//购买价格
            "color"=>"#9b9b9b"
        ),
    );
    if($type =='shop'){
        $page = "pages/mine/shop/order/list?shop_id=".$info['shop_id']."&wid=".$info['wid'];//打开页面
    }
    if($type == 'member'){
        $page = "pages/mine/mine";//打开页面
    }
    if(!$type){
        $page = "pages/index/index";//打开页面
    }

    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
//    $str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
//    file_put_contents('o.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendOrderMessage($openid,$out_trade_no,$wid);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送核销成功通知
 * 核销支付成功后用户收到模板消息，同时商家也要收到消息
 * @param $openid       opneid
 * @param $out_trade_no  订单号
 * @param $type 类型。商家shop 用户member
 * @return bool
 */
function sendQrcodeMessage($openid,$out_trade_no,$wid,$type)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%购买成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('shop_recharge_log')->alias('l')->field("l.*,s.name")->join('tp_shop s on s.shop_id = l.shop_id')->where(['out_trade_no'=>$out_trade_no])->find();
    //组装data

    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$info['name'], //购买地点
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$info['create_time'], //购买时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>'线下核销消费',//物品名称
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$out_trade_no,//交易单号
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>"￥".$info['money']."元",//购买价格
            "color"=>"#9b9b9b"
        ),
    );
    if($type =='shop'){
        $page = "pages/mine/shop/order/list?shop_id=".$info['shop_id']."&wid=".$info['wid'];//打开页面
    }
    if($type == 'member'){
        $page = "pages/mine/mine";//打开页面
    }
    if(!$type){
        $page = "pages/index/index";//打开页面
    }

    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
//    $str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n';
//    file_put_contents('o.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendQrcodeMessage($openid,$out_trade_no,$wid);
    }
    if($result['errcode'] == 0  ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}



/*
 * 拼团成功模板消息
 * 发送给团长和参团的人以及商家
 */
function sendTuanMessage($openid,$out_trade_no,$wid)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }

    //查出模板id
    $where['title'] = array("like","%拼团成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //判断是团长还是个人
    $order = M("order")->where(['out_trade_no'=>$out_trade_no])->find();
    if($order['is_tuan'] && $order['is_tuan_first']){
        //团长
        $user = M('user')->where(['openid'=>$order['openid'],'wid'=>$order['wid']])->find();
    }else{
        //团员
        $tuan = M("order")->where(['id'=>$order['tuan_first_id']])->find();
        $user = M('user')->where(['openid'=>$tuan['openid'],'wid'=>$order['wid']])->find();
    }
    if(!$user){
        return false;
    }
    //商品原价
    $goods = M('goods')->where(['id'=>$order['goods_id']])->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$order['title'], //活动名称
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$user['nickname'], //团长
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$order['tuan_need_num'],//成团人数
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$order['title'],//商品名称
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$goods['price'],//商品金额
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>$tuan?$tuan['create_time']:$order['create_time'],//开团时间
            "color"=>"#9b9b9b"
        ),
        "keyword7"=>array(
            "value"=>$order['price'],//拼团价
            "color"=>"#9b9b9b"
        ),
        "keyword8"=>array(
            "value"=>"如果未按承诺时间发货，系统将按照规则进 行赔偿。",//温馨提示
            "color"=>"#9b9b9b"
        ),
        "keyword9"=>array(
            "value"=>$out_trade_no,//提货码
            "color"=>"#9b9b9b"
        )
    );

    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendTuanMessage($openid,$out_trade_no,$wid);
    }
    if($result['errcode'] == 0 ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送砍价进度通知
 * 砍价进度通知
 * @param $openid       opneid
 * @param $kanid  砍价日志表id
 * @param $kan_num  已有几人砍价
 * @param $kan_total  已砍价多少钱
 * @param $wid  wid
 * @return bool
 */
function sendKanMessage($openid,$kanid,$kan_num,$kan_total,$wid,$type)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%砍价进度%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('goods')->alias('g')->field("k.*,g.title,g.price,g.stock,g.kan_price")
                ->join('tp_kan_log k on k.goods_id = g.id')
                ->where(['k.id'=>$kanid])
                ->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid

    if($type == "ing"){
        //砍价进度
        $value = array(
            "keyword1"=>array(
                "value"=>$info['title'], //商品名称
                "color"=>"#4a4a4a"
            ),
            "keyword2"=>array(
                "value"=>"已有".$kan_num."人砍价", //砍价进度
                "color"=>"#9b9b9b"
            ),
            "keyword3"=>array(
                "value"=>"20时35分17秒",//剩余时间
                "color"=>"#9b9b9b"
            ),
            "keyword4"=>array(
                "value"=>"留给你的时间不多了，快召集好友吧！",//温馨提示
                "color"=>"#9b9b9b"
            ),
            "keyword5"=>array(
                "value"=>$info['stock'],//商品库存
                "color"=>"#9b9b9b"
            ),
            "keyword6"=>array(
                "value"=>"￥".$info['price']."元",//支付金额
                "color"=>"#9b9b9b"
            ),
            "keyword7"=>array(
                "value"=>"￥".$kan_total."元",//砍价金额
                "color"=>"#9b9b9b"
            ),
            "keyword8"=>array(
                "value"=>"￥".intval($info['price'] - $kan_total)."元",//当前价格
                "color"=>"#9b9b9b"
            ),
            "keyword9"=>array(
                "value"=>date("Y-m-d H:i:s",strtotime("+1 days",time())),//结束时间
                "color"=>"#9b9b9b"
            )
        ) ;
    }else{
        //砍价成功
        //砍价进度
        $value = array(
            "keyword1"=>array(
                "value"=>$info['title'], //商品名称
                "color"=>"#4a4a4a"
            ),
            "keyword2"=>array(
                "value"=>"已有".$kan_num."人砍价", //砍价进度
                "color"=>"#9b9b9b"
            ),
            "keyword3"=>array(
                "value"=>"20时35分17秒",//剩余时间
                "color"=>"#9b9b9b"
            ),
            "keyword4"=>array(
                "value"=>"您可以告知您的好友砍价成功哦!",//温馨提示
                "color"=>"#9b9b9b"
            ),
            "keyword5"=>array(
                "value"=>$info['stock'],//商品库存
                "color"=>"#9b9b9b"
            ),
            "keyword6"=>array(
                "value"=>"￥".$info['price']."元",//支付金额
                "color"=>"#9b9b9b"
            ),
            "keyword7"=>array(
                "value"=>"￥".$kan_total."元", //砍价金额
                "color"=>"#9b9b9b"
            ),
            "keyword8"=>array(
                "value"=>"￥".intval($info['price'] - $kan_total)."元",//当前价格
                "color"=>"#9b9b9b"
            ),
            "keyword9"=>array(
                "value"=>date("Y-m-d H:i:s",strtotime("+1 days",time())),//结束时间
                "color"=>"#9b9b9b"
            )

        ) ;
    }


    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    //$str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n'.'sql=';
    //file_put_contents('o123.txt',$str,FILE_APPEND);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendKanMessage($openid,$kanid,$kan_num,$kan_total,$wid,$type);
    }
    if($result['errcode'] == 0 ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送请购成功通知
 * @param $openid       opneid
 * @param $out_trade_no  订单号
 * @return bool
 */
function sendQiangMessage($openid,$out_trade_no,$wid)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%抢购成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('order')->alias('o')->field("o.*,s.name,s.cid")->join('tp_shop s on s.shop_id = o.shop_id')->where(['out_trade_no'=>$out_trade_no])->find();
    $cate = M('cate')->where(['id'=>$info['cid']])->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid

    $value = array(
        "keyword1" => array(
            "value" => $info['title'], //商品名称
            "color" => "#4a4a4a"
        ),
        "keyword2" => array(
            "value" => $info['name'], //商品价格
            "color" => "#9b9b9b"
        ),
        "keyword3" => array(
            "value" => $info['create_time'],//抢购时间
            "color" => "#9b9b9b"
        ),
        "keyword4" => array(
            "value" => $cate?$cate['title']:'美食',//产品类型
            "color" => "#9b9b9b"
        ),
        "keyword5" => array(
            "value" => "线下核销",//产品服务
            "color" => "#9b9b9b"
        ),
        "keyword6" => array(
            "value" => $info['name'] ,//商户名称
            "color" => "#9b9b9b"
        ),
        "keyword7" => array(
            "value" => "1" ,//购买数量
            "color" => "#9b9b9b"
        ),
        "keyword8" => array(
            "value" => "￥" . $info['pay_money']  . "元",//总金额
            "color" => "#9b9b9b"
        ),
        "keyword9" => array(
            "value" => date("Y-m-d H:i:s", strtotime("+1 days", time())),//消费截止
            "color" => "#9b9b9b"
        )
    );

    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
//    $str = 'dd='.json_encode($dd).'\r\n'.'code='.$result['errcode'] .'\r\n'.'msg='.$result['errmsg'].'\r\n'.'sql=';
//    file_put_contents('o123.txt',$str,FILE_APPEND);

    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendQiangMessage($openid,$out_trade_no,$wid);
    }
    if($result['errcode'] == 0 ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
//提现成功通知！
function sendWithdrawMessage($openid,$withdrawid)
{
    //获取微信的access_token
    $access_token = get_access_token_mp();
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出提现内容
    $withdraw = M('withdraw')->where(array('id'=>$withdrawid))->find();
    if(!$withdrawid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%提现到账%");
    $where['wid'] = session('wid');
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$withdraw['real_money'], //到账金额
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$withdraw['apply_money'], //提现金额
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$withdraw['rate']."%",//手续费
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>"微信钱包",//提现至
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$withdraw['remit_time'],//到账时间
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>$withdraw['createtime'],//提现申请时间
            "color"=>"#9b9b9b"
        ),
        "keyword7"=>array(
            "value"=>"提现已发至您的微信钱包，请查收",//温馨提示
            "color"=>"#9b9b9b"
        )
    );
    if($withdraw['shop_id']){
        //商家提现 之后还有用户提现等，故加判断
        $page = "pages/index/index?shop_id={$withdrawid['shop_id']}&wid={$withdrawid['wid']}";//打开页面
    }


    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 41028 || $result['errcode'] == 41029){
        M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        //发送失败重新发送
        sendWithdrawMessage($openid,$withdrawid);
    }
    if($result['errcode'] == 0 ){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

//获取微信公众平台token
function get_access_token_mp($wid)
{
    $wid = session('wid')?session('wid'):$wid;
    $wechat = M('wechat')->where(array('wid'=>$wid))->find();
    /*$token = S("access_token_mp");
    if($token){
        return $token;
    }*/
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['app_secret']}";
    $res = ihttp_get($url);
    $td = json_decode($res, true);
    if($td['access_token']){
        S("access_token_mp", $td['access_token'], $td['expires_in'] - 120);
        return $td['access_token'];
    }else{
        return false;
    }
}

function ihttp_post($url, $post_data){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}

function ihttp_get($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}
